package com.dabaozhan.modules.wx_app.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.dabaozhan.common.exception.RRException;
import com.dabaozhan.common.utils.ImageOperation;
import com.dabaozhan.common.utils.UploadFile;
import com.dabaozhan.common.utils.aliyun.ocr.IndustryUtils;
import com.dabaozhan.modules.wx_app.base.ResponseDto;
import com.dabaozhan.modules.wx_app.entity.CardEntity;
import com.dabaozhan.modules.wx_app.entity.SiteIndustryEntity;
import com.dabaozhan.modules.wx_app.entity.UserEntity;
import com.dabaozhan.modules.wx_app.enums.ResponseCodeEnum;
import com.dabaozhan.modules.wx_app.service.CardService;
import com.dabaozhan.modules.wx_app.service.SiteIndustryService;
import com.dabaozhan.modules.wx_app.service.UserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;

/**
 * @author houzhong
 * @date 2019-01-09 20:48
 *
 * 营业执照
 */
@Api(value = "营业执照", description = "营业执照")
@RestController
@RequestMapping("/wx_app")
public class SiteIndustryController {

    private static final Logger LOGGER = LoggerFactory.getLogger(SiteIndustryController.class);

    /**行业认证*/
    @Autowired
    private SiteIndustryService siteIndustryService;

    /**身份证*/
    @Autowired
    private CardService cardService;

    /**用户*/
    @Autowired
    private UserService userService;

    @ApiOperation(value = "查询营业执照身份证信息")
    @RequestMapping("/getCertificatesUserId")
    public String getIndustry(String userId){
        ResponseDto<SiteIndustryEntity> responseDto = new ResponseDto<SiteIndustryEntity>();
        try {
            SiteIndustryEntity v = siteIndustryService.findByCertificatesUserId(userId);
            if (v != null) {
                responseDto.setResponseCodeEnum(ResponseCodeEnum.ResponseCode_100);
                responseDto.setResult(v);
            }else {
                responseDto.setResponseCodeEnum(ResponseCodeEnum.ResponseCode_400);
            }
        } catch(RRException re){
            responseDto.setCode(re.getCode());
            responseDto.setMessage(re.getMessage());
        } catch (Exception e) {
            responseDto.setResponseCodeEnum(ResponseCodeEnum.ResponseCode_500);
            //记录异常日志
            LOGGER.error("查询营业执照信息发生异常:",e);
        } finally {
            //记录请求入参和返回日志
            LOGGER.info("查询营业执照信息发生异常:{}-返回结果:{}", JSON.toJSONString(responseDto));
        }
        return JSON.toJSONString(responseDto);
    }

    @ApiOperation(value = "上传营业执照")
    @RequestMapping("/uploadIndustryFile")
    public String uploadIndustryFile(@RequestParam(value = "file", required = false) MultipartFile[] file,HttpServletRequest request) {
        ResponseDto<SiteIndustryEntity> responseDto = new ResponseDto<SiteIndustryEntity>();
        try {
            request.setCharacterEncoding("UTF-8");
            //用户id
            String userId =  request.getParameter("userId");
            LOGGER.info("用户id{}",JSON.toJSONString(userId));
            //图片保存路径
            String pathUrl = request.getSession().getServletContext().getRealPath("/")+ ("fileImage/");
            LOGGER.info("图片路径{}",JSON.toJSONString(pathUrl));

            JSONObject jsonObject = UploadFile.uploadFileImg(file,pathUrl);
            LOGGER.info("解析营业执照数据{}",JSON.toJSONString(jsonObject));

            //图片名称
            String targetFileName = jsonObject.getString("targetFileName");

            //解析身份证信息
            JSONObject res_obj = IndustryUtils.getIndustry(pathUrl + targetFileName);

            if (res_obj != null) {
                //统一社会信用代码
                String unifiedCode = res_obj.getString("reg_num");
                //注册资金
                String registeredCapital = res_obj.getString("capital");
                //注册地址
                String residence = res_obj.getString("address");
                //企业名称
                String name = res_obj.getString("name");
                //法人
                String legalPerson = res_obj.getString("person");

                SiteIndustryEntity siteIndustry = new SiteIndustryEntity();
                siteIndustry.setUserId(userId);
                siteIndustry.setImg(pathUrl + targetFileName);
                siteIndustry.setName(name);
                siteIndustry.setResidence(residence);
                siteIndustry.setUnifiedCode(unifiedCode);
                siteIndustry.setRegisteredCapital(registeredCapital);
                siteIndustry.setLegalPerson(legalPerson);

                responseDto.setResponseCodeEnum(ResponseCodeEnum.ResponseCode_100);
                responseDto.setResult(siteIndustry);

            }else {
                responseDto.setResponseCodeEnum(ResponseCodeEnum.ResponseCode_302);
            }
        } catch(RRException re){
            responseDto.setCode(re.getCode());
            responseDto.setMessage(re.getMessage());
        } catch (Exception e) {
            responseDto.setResponseCodeEnum(ResponseCodeEnum.ResponseCode_500);
            //记录异常日志
            LOGGER.error("上传营业执照发生异常:",e);
        } finally {
            //记录请求入参和返回日志
            LOGGER.info("上传营业执照发生异常:{}-返回结果:{}",JSON.toJSONString(responseDto));
        }
        return JSON.toJSONString(responseDto);
    }

    @ApiOperation(value = "保存和修改营业执照(身份证)信息")
    @RequestMapping("/saveSiteIndustry")
    public String saveSiteIndustry(SiteIndustryEntity v,HttpServletRequest request) {
        ResponseDto<SiteIndustryEntity> responseDto = new ResponseDto<SiteIndustryEntity>();
        try {
            //图片保存路径
            String pathUrl = request.getSession().getServletContext().getRealPath("/")+ ("fileImage/");
            //获取文件目录图片
            String url = ImageOperation.encodeImage(v.getImg().substring(v.getImg().lastIndexOf("/") + 1), pathUrl);

            //身份证图片
            String cardUrl = ImageOperation.encodeImage(v.getCardUrl().substring(v.getCardUrl().lastIndexOf("/") + 1), pathUrl);

            //身份证信息
            CardEntity card = new CardEntity();
            card.setCardNum(v.getCardNum());
            card.setCardAddress(v.getCardAddress());
            card.setCardSex(v.getCardSex());
            card.setCardName(v.getCardName());
            card.setCardBirth(v.getCardBirth());
            card.setCardUrl(cardUrl);
            card.setUserId(v.getUserId());

            SiteIndustryEntity siteIndustry = siteIndustryService.findByUserId(v.getUserId());
            if (siteIndustry != null) {
                siteIndustry.setImg(url);
                siteIndustry.setRegisteredCapital(v.getRegisteredCapital());
                siteIndustry.setUnifiedCode(v.getUnifiedCode());
                siteIndustry.setResidence(v.getResidence());
                siteIndustry.setName(v.getName());
                siteIndustry.setLegalPerson(v.getLegalPerson());
                siteIndustry.setRange(v.getRange().substring(0,v.getRange().length()-1));
                siteIndustry.setLegalPerson(v.getLegalPerson());

                siteIndustryService.updateSiteIndustry(siteIndustry);

                //修改身份证信息
                card = cardService.findByCardUserId(v.getUserId());

                cardService.updateCard(card);

                responseDto.setResponseCodeEnum(ResponseCodeEnum.ResponseCode_100);
                responseDto.setResult(siteIndustry);
            }else {
                v.setImg(url);
                siteIndustryService.saveSiteIndustry(v);

                cardService.saveCard(card);

                UserEntity user = userService.findByUserId(v.getUserId());
                if (user != null) {
                    //认证成功
                    user.setAuditStatus(3);
                    userService.updateUser(user);
                }
                responseDto.setResponseCodeEnum(ResponseCodeEnum.ResponseCode_100);
                responseDto.setResult(v);
            }
        } catch(RRException re){
            responseDto.setCode(re.getCode());
            responseDto.setMessage(re.getMessage());
        } catch (Exception e) {
            responseDto.setResponseCodeEnum(ResponseCodeEnum.ResponseCode_500);
            //记录异常日志
            LOGGER.error("保存和修改营业执照信息:",e);
        } finally {
            //记录请求入参和返回日志
            LOGGER.info("保存和修改营业执照信息发生异常:{}-返回结果:{}",JSON.toJSONString(responseDto));
        }
        return JSON.toJSONString(responseDto);
    }
}
